package models

import (
	"fmt"
	"git.inedcn.com/ined/cmn"
	"github.com/gin-gonic/gin"
	"log"
	"rongyy/src/app"
	"rongyy/src/middlewares"
)

type WxUserInfo struct {
	Nickname  string `json:"nickName"`
	Gender    int8   `json:"gender"`
	Language  string `json:"language"`
	City      string `json:"city"`
	Province  string `json:"province"`
	Country   string `json:"country"`
	AvatarUrl string `json:"avatarUrl"`
}

type ReqWxLogin struct {
	Code          string     `json:"code"`
	EncryptedData string     `json:"encrypted_data"`
	Iv            string     `json:"iv"`
	UserInfo      WxUserInfo `json:"userInfo"`
	Appid         string     `json:"appid"`
	Secret        string     `json:"secret"`
}

type UserModel struct {
	BaseModel      `xorm:"extends"`
	Subscribe      int8     `json:"subscribe"`
	Openid         string   `json:"openid"`
	Nickname       string   `json:"nickname"`
	Sex            int8     `json:"sex"`
	Language       string   `json:"language"`
	Province       string   `json:"province"`
	City           string   `json:"city"`
	Country        string   `json:"country"`
	Headimgurl     string   `json:"headimgurl"`
	SubscribeTime  int64    `json:"subscribe_time"`
	Unionid        string   `json:"unionid"`
	Remark         string   `json:"remark"`
	Groupid        int8     `json:"groupid"`
	TagidList      []string `json:"tagid_list"`
	SubscribeScene string   `json:"subscribe_scene"`
	QrScene        int8     `json:"qr_scene"`
	QrSceneStr     string   `json:"qr_scene_str"`
	Errcode        int      `json:"errcode" xorm:"-"`
	MpOpenid       string   `json:"mp_openid"`
}

type ReqUnionid struct {
	Unionid  string `form:"user" json:"unionid" xml:"user"  binding:"required"`
	Hospital string `json:"hospital" xorm:"-"`
}

type ReqId struct {
	Id       int64  `json:"id"`
	Hospital string `json:"hospital" xorm:"-"`
}

type ReqUpdateMpOpenid struct {
	Unionid  string `form:"user" json:"unionid" xml:"user"`
	MpOpenid string `form:"user" json:"mp_openid" xml:"user"`
	Hospital string `json:"hospital" xorm:"-"`
}

type ReqGetCards struct {
	Openid   string `form:"user" json:"openid" xml:"user"`
	Unionid  string `form:"user" json:"unionid" xml:"user"`
	Hospital string `json:"hospital" xorm:"-"`
}

type CardsModel struct {
	CardNo     string `json:"cardNo"`
	RealName   string `json:"realName"`   // 生成的订单号
	Sex        int    `json:"sex"`        // 状态 0启用 1停用
	Age        int    `json:"age"`        // 0 默认值 1删除
	Mobile     string `json:"mobile"`     // 备注
	IdNo       string `json:"idNo"`       // 创建时间
	Occupation string `json:"occupation"` // 创建人
	Empi       string `json:"empi"`       // 创建人
	Hospital   string `json:"hospital" xorm:"-"`
}

func (u *UserModel) TableName() string {
	return "wx_userinfo"
}

func (wx *UserModel) Insert() error {
	_, err := app.DB().Insert(wx)
	if err != nil {
		middlewares.Logger.Println("DEBUG - WxUser Insert failed ", err)
		return err
	}
	return nil
}

func (wx *UserModel) Get() (bool, error) {
	exist, err := app.DB().Where("unionid = ?", wx.Unionid).Get(wx)
	if err != nil {
		middlewares.Logger.Println("DEBUG - WxUser Get failed ", exist, err)
		return exist, err
	}
	return exist, nil
}

func (this *UserModel) String() string {
	return fmt.Sprintf("userid")
}

func (this *UserModel) UserList(ctx *gin.Context) string {
	return "UserList"
}

func (u *UserModel) Create(user *UserModel) error {
	_, err := app.DB().Insert(user)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func (u *UserModel) FindByUnionid(unionId string) (*UserModel, bool, error) {
	user := new(UserModel)
	has, err := app.DB().Where("unionid = ?", unionId).Get(user)
	if err != nil {
		return nil, has, err
	}
	return user, has, nil
}

func (u *UserModel) FindById(id int64) (*UserModel, bool, error) {
	// user := new(UserModel)
	user := &UserModel{}
	fmt.Println("app.DB: ", id)
	has, err := app.DB().Where("id = ?", id).Get(user)
	if err != nil {
		log.Println("errrrrrrrrrrr: ", err)
		return nil, has, err
	}
	return user, has, nil
}

func (um *UserModel) UpdateOpenid(unionId string, openid string) error {
	user := new(UserModel)
	_, err := app.DB().Where("unionid = ?", unionId).Get(user)
	user.MpOpenid = openid
	_, err = app.DB().ID(user.Id).Cols("mp_openid").Update(user)
	if err != nil {
		return err
	}
	return err
}

func (um *UserModel) FindCardsByUnionid(unionid string) ([]CardModel, int64, error) {
	cards := make([]CardModel, 0)
	total, err := app.DB().Table("ho_patientcard_item").Alias("hpi").
		Join("RIGHT", "ho_patientcard AS hp", "hpi.patient_id = hp.id").
		Select("hp.source_id, hp.card_no, hp.ecard_no, hp.real_name,  hp.sex, hp.age, hp.mobile, hp.id_no, hp.occupation, hp.empi").
		Where("hpi.unionid = ? and status = 1", unionid).FindAndCount(&cards)
	log.Println("decode: ", cards)
	log.Println("decode: ", err)

	if err != nil {
		return nil, 0, err
	}
	return cards, total, nil
}

func (um *UserModel) GetAll(hospital string) ([]UserModel, error) {
	users := make([]UserModel, 0)
	// err := app.DB(hospital).Limit(5000, 1).Find(&users)
	err := app.DB().Find(&users)
	if err != nil {
		return nil, err
	}
	return users, nil
}

func (um *UserModel) UpdateUnionidByWxId(id int64, unionId string, hospital string) error {
	user := new(UserModel)
	user.Unionid = unionId
	_, err := app.DB().Where("id = ?", id).Cols("unionid").Update(user)
	if err != nil {
		return err
	}
	return err
}

func (wx *UserModel) UpdateMpOpenid(unionId string) error {
	_, err := app.DB().Where("unionid = ?", unionId).Cols("mp_openid").Update(wx)
	if err != nil {
		middlewares.Logger.Println("DEBUG - WxUser UpdateMpOpenid failed ", err)
		return err
	}
	return nil
}

type NewWxUser struct {
	Id             int64        `xorm:"pk autoincr" json:"id"`
	Subscribe      int8         `json:"subscribe"`
	Openid         string       `json:"openid"`
	Nickname       string       `json:"nickname"`
	Sex            int8         `json:"sex"`
	Language       string       `json:"language"`
	Province       string       `json:"province"`
	City           string       `json:"city"`
	Country        string       `json:"country"`
	Headimgurl     string       `json:"headimgurl"`
	SubscribeTime  int64        `json:"subscribe_time"`
	Unionid        string       `json:"unionid"`
	Remark         string       `json:"remark"`
	Groupid        int8         `json:"groupid"`
	TagidList      []string     `json:"tagid_list"`
	SubscribeScene string       `json:"subscribe_scene"`
	QrScene        int8         `json:"qr_scene"`
	QrSceneStr     string       `json:"qr_scene_str"`
	Errcode        int          `json:"errcode" xorm:"-"`
	CreatedAt      cmn.JsonTime `xorm:"created" json:"created_at"`
	UpdatedAt      cmn.JsonTime `xorm:"updated" json:"updated_at"`
	DeletedAt      cmn.JsonTime `xorm:"deleted" json:"-"`
}

//
//func (um *UserModel) CreateNewWxUser(hospital string, user *NewWxUser) error {
//	newuser := &NewWxUser{}
//	has, err := app.ScszlDB().Table("wx_user").Where("openid = ?", user.Openid).Get(newuser)
//	if has {
//		println("has", newuser.Openid)
//	}
//	if err != nil {
//		return err
//	}
//	if !has {
//		_, err = app.ScszlDB().Table("wx_user").Insert(user)
//	}
//	if err != nil {
//		return err
//	}
//	println(user.Id)
//	return nil
//}
//
//func (um *UserModel) GetAllUsersWithoutUnionid(hospital string, limit int, offset int) ([]NewWxUser, int64, error) {
//	newuser := make([]NewWxUser, 0)
//	total, err := app.ScszlDB().Table("wx_user").Where("unionid = '' and id > ? and id <= ?", offset, offset+limit).FindAndCount(&newuser)
//	if err != nil {
//		return nil, 0, err
//	}
//	return newuser, total, nil
//}
//
//func (um *UserModel) UpdateNewWxUser(hospital string, user *NewWxUser) error {
//	_, err := app.ScszlDB().Table("wx_user").Where("openid = ?", user.Openid).Update(user)
//	if err != nil {
//		return err
//	}
//	println(user.Id, user)
//	return nil
//}

func (u *UserModel) FindByECard(cardno string) (*UserModel, bool, error) {
	// user := new(UserModel)
	user := &UserModel{}
	has, err := app.DB().Where("ecard_no = ?", cardno).Get(user)
	if err != nil {
		log.Println("errrrrrrrrrrr: ", err)
		return nil, has, err
	}
	return user, has, nil
}
